import { Button, NavBar, Form, Input, Toast } from "antd-mobile"
import { LoginForm, LoginResponse } from "@/types/data"
import styles from "./index.module.scss"
import { useDispatch } from "react-redux"
import { login, sendCode } from "@/store/actions/login"
import { customHistory } from "@/utils/history"
import { AxiosError } from "axios"
import { useRef, useState, useEffect } from "react"
import { InputRef } from "antd-mobile/es/components/input"
import { useLocation } from "react-router-dom"
const Login = () => {
  const dispatch = useDispatch()
  const [form] = Form.useForm()
  const mobileRef = useRef<InputRef>(null)
  const timeRef = useRef(-1)
  const [timeLeft, setTimeLeft] = useState(0)
  // 注意： state 可能是不存在的，所以，类型中要明确包含不存在的情况，即 undefined
  const location = useLocation<{ from: string } | undefined>()
  const onFininsh = async (values: LoginForm) => {
    try {
      await dispatch(login(values))
      // 成功
      Toast.show({
        content: "登录成功",
        duration: 600,
        afterClose: () => {
          if (location.state) {
            return customHistory.replace(location.state.from)
          }
          customHistory.replace("/home/index")
        },
      })
    } catch (e) {
      const error = e as AxiosError<{ message: string }>
      Toast.show({
        content: error.response?.data?.message,
        duration: 1000,
      })
    }
  }
  // 发送验证码
  const onSendCode = async () => {
    // 获取手机号
    const mobile = form.getFieldValue("mobile") || ""
    const isError = form.getFieldError("mobile").length
    if (isError || mobile?.trim() === "") {
      return mobileRef.current?.focus()
    }
    try {
      await dispatch(sendCode(mobile))
      Toast.show({
        content: "验证码已发送",
      })
      setTimeLeft(5)
      timeRef.current = window.setInterval(() => {
        setTimeLeft((timeLeft) => timeLeft - 1)
        console.log("当前的状态:", timeLeft)
      }, 1000)
    } catch (e) {
      const error = e as AxiosError<{
        message: string
        response: { data: LoginResponse }
      }>
      Toast.show({
        content: error.response?.data.message,
      })
    }
  }
  useEffect(() => {
    if (timeLeft === 0) {
      window.clearInterval(timeRef.current)
    }
    // 这里返回的函数每次状态更新的时候都会执行 所以这里 不能做处理

    // return () => {}
  }, [timeLeft])
  useEffect(() => {
    return () => {
      window.clearInterval(timeRef.current)
    }
  }, [])
  return (
    <div className={styles.root}>
      <NavBar></NavBar>

      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form form={form} onFinish={onFininsh}>
          <Form.Item
            className="login-item"
            name="mobile"
            rules={[
              {
                required: true,
                message: "请输入手机号",
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: "手机号格式不正确",
              },
            ]}
          >
            <Input placeholder="请输入手机号" maxLength={11} ref={mobileRef} />
          </Form.Item>

          <Form.Item
            className="login-item"
            name="code"
            extra={
              <span
                className="code-extra"
                onClick={timeLeft === 0 ? onSendCode : undefined}
              >
                {timeLeft === 0 ? "发送验证码" : `${timeLeft}s后重新获取`}
              </span>
            }
            rules={[
              {
                required: true,
                message: "请输入验证码",
              },
              {
                pattern: /^\d{6}$/,
                message: "验证码格式不正确",
              },
            ]}
          >
            <Input
              placeholder="请输入验证码"
              autoComplete="off"
              maxLength={6}
            />
          </Form.Item>

          {/* noStyle 表示不提供 Form.Item 自带的样式 */}
          <Form.Item noStyle shouldUpdate>
            {() => {
              // 处理逻辑
              // 得到禁用状态
              const disabled =
                form.getFieldsError().filter((item) => item.errors.length > 0)
                  .length > 0 || !form.isFieldsTouched(true)
              return (
                <Button
                  block
                  type="submit"
                  color="primary"
                  className="login-submit"
                  disabled={disabled}
                >
                  登 录
                </Button>
              )
            }}
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login
